package com.love.netty.demo.handler.request;

import com.love.netty.core.packet.request.QuitGroupRequestPacket;
import com.love.netty.core.packet.response.QuitGroupResponsePacket;
import com.love.netty.util.SessionUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @ClassName: QuitGroupRequestHandler
 * @Description: 瑞出群
 * @Author: wuj
 * @Date: 2021-06-25 15:35
 **/
@ChannelHandler.Sharable
public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {

    public static final QuitGroupRequestHandler INSTANCE = new QuitGroupRequestHandler();

    private QuitGroupRequestHandler() {

    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, QuitGroupRequestPacket quitGroupRequestPacket) throws Exception {
        //获取对应的组id
        String groupId = quitGroupRequestPacket.getGroupId();
        ChannelGroup channelGroup = SessionUtils.getChannelGroup(groupId);
        //退出群聊需要移除当前绑定的channel
        channelGroup.remove(channelHandlerContext.channel());

        //创建退群响应包
        QuitGroupResponsePacket quitGroupResponsePacket = new QuitGroupResponsePacket();
        quitGroupResponsePacket.setGroupId(groupId);
        quitGroupResponsePacket.setSuccess(true);
        channelHandlerContext.channel().writeAndFlush(quitGroupResponsePacket);
    }
}
